import re
from rest_framework import serializers
from django_redis import get_redis_connection
from users.models import User, Address
from celery_tasks.email.tasks import send_verify_email


class CreateUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'password2', 'sms_code', 'allow', 'mobile', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5～20个字符的用户名',
                    'max_length': '仅允许5～20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8～20个字符的密码',
                    'max_length': '仅允许8～20个字符的密码',
                }
            }
        }

    def validate_allow(self, value):
        """检查用户是否同意用户协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议！')
        return value

    def validate_mobile(self, mobile):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            raise serializers.ValidationError('手机号错误！')
        count = User.objects.filter(mobile=mobile).count()
        if count > 0:
            raise serializers.ValidationError('手机号已被注册！')
        return mobile

    def validate(self, attrs):
        # 判断密码
        password = attrs.get('password')
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError('两次输入的密码不一致！')
        # 判断短信验证码
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        redis = get_redis_connection('verify_code')
        try:
            real_sms_code = redis.get('sms_%s' % mobile).decode()
        except Exception as e:
            raise serializers.ValidationError('短信不存在或已过期！')
        if sms_code != real_sms_code:
            raise serializers.ValidationError('短信验证码错误！')
        return attrs

    def create(self, validated_data):
        """创建用户"""
        # 删除不用保存的数据
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        user = super().create(validated_data)
        # 调用django的认证系统加密密码
        user.set_password(validated_data['password'])
        user.save()
        # 使用jwt来保存用户登陆状态
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


class EmailSerializer(serializers.ModelSerializer):
    """邮箱序列化器"""

    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwagrs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = email
        instance.save()

        # 生成验证链接
        verify_url = instance.generate_verify_email_url()
        print(verify_url)
        # 发送验证邮件
        send_verify_email.delay(email, verify_url)
        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    # 声明字段
    # 用于显示给客户端浏览器的地址信息[增加__str__方法的关联]
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)

    # 设置保存到数据表的id信息[取消关联]
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        # 表示排除掉列表中设置的字段，剩下的字段都要在序列化器使用
        exclude = ['user', 'is_deleted', 'create_time', 'update_time']

    # 校验数据
    def validate_mobile(self, value):
        """校验手机号码"""
        print(value)
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号错误！')
        return value

    def create(self, validated_data):
        # 获取当前登陆用户
        # self.context  就是实例化序列化器时的第三个参数，可以允许视图那边传递数据到序列化器中
        # self.context　提供了三个参数： view视图对象, request请求对象, format参数的格式
        # 在GenericAPIView里面的get_serializer方法中默认帮我们把视图对象传递到了序列化器中了
        # 当前已经登陆的用户保存到过滤后的数据中
        validated_data['user'] = self.context['request'].user
        # 调用原来drf的序列化器的保存方法
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ['title']
